package com.wf.demo.info.service;

import com.wf.demo.info.dao.AlarmDAO;
import com.wf.demo.info.pojo.Device;
import com.wf.demo.info.dao.DeviceDAO;
import com.wf.demo.info.pojo.Alarm;
import com.wf.demo.info.pojo.Parse;
import com.wf.demo.info.util.LocalDateTimeUtils;
import com.wf.demo.info.util.Page4Navigator;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.wf.demo.info.service.DeviceService;


import javax.validation.constraints.Null;
import java.math.BigDecimal;
import java.security.PublicKey;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class AlarmService {
    @Autowired
    AlarmDAO alarmDAO;
    @Autowired
   DeviceService deviceService;
    @Autowired
    MatchService matchService;

    //查找单个设备所有故障记录
    public Page4Navigator<Alarm> list(Long did, int start, int size, int navigatePages){
        Device device=deviceService.get(did);
        Sort sort = new Sort(Sort.Direction.DESC, "id");  //id倒序排序，最新的记录在最前面
        Pageable pageable = new PageRequest(start, size, sort);
        Page pageFromJPA = alarmDAO.findByDevice(device,pageable);
        return new Page4Navigator<>(pageFromJPA,navigatePages);
    }
    //查找所有设备所有最新故障记录
    public Page4Navigator<Alarm> list( int start, int size, int navigatePages){
        Sort sort = new Sort(Sort.Direction.DESC, "id");  //id倒序排序，最新的记录在最前面
        Pageable pageable = new PageRequest(start, size, sort);
        Page pageFromJPA = alarmDAO.findAll(pageable);
        return new Page4Navigator<>(pageFromJPA,navigatePages);
    }
    //增删改查
    public void add(Alarm bean){
        alarmDAO.save(bean);
    }
    public void update(Alarm bean){
        alarmDAO.save(bean);
    }
    public void delete(Long id){
        alarmDAO.delete(id);
    }
    public Alarm get(Long id){
        return alarmDAO.findOne(id);
    }

    //业务代码报警
    public  Alarm judgeAlarm(Parse parse, BigDecimal dataValue,Device device){
        //如果是故障码得找到匹配信息才能产生报警信息
        String dataIdentifier= parse.getDataIdentifier();
        BigDecimal minValue =parse.getMinValue();
        BigDecimal maxValue =parse.getMaxValue();
        boolean isMatch =parse.isMatch();  //不需要匹配时就必须检验数据是否超标
        Alarm alarm=new Alarm();
        alarm.setDevice(device);  //绑定设备
        alarm.setAlarmType(2);  //默认类型为2，即不存在异常信息，方便parse
        //如果是故障码
        if(dataIdentifier.equals("alarmCode")){
            String alarmInfo = matchService.getStringByMatch(parse,dataValue);
            if( ! alarmInfo.equals("默认正常") ){
                alarm.setAlarmType(1);  //类型1表示是故障码故障
                alarm.setAlarmInfo(alarmInfo);
            }
        }
        //查看数据是否超标 （所有严格规定有阈值的）
        if(isMatch == false){
            if(minValue ==null) //阈值不存在时退出程序
              return alarm;
            if(  (dataValue.compareTo(maxValue)==1) ||(dataValue.compareTo(minValue)== -1) ){
                alarm.setAlarmType(0);
                alarm.setAlarmInfo(parse.getDataIdentifier()+"数据超标");
            }
        }
        return  alarm;
    }
    //即报警状态的设备接收到了正常的数据，需要对ALarm写入endTime
        public void  setEndTime(Device device){
            LocalDateTime nowTime= LocalDateTime.now();
            //先找到设备下endTime为空的所有alarm,即还未被处理的alarm
            List<Alarm>  alarms=alarmDAO.findByDeviceAndEndTime(device,null);
            //写入endTime,别忘了存入数据库
            for(Alarm alarm: alarms){
                alarm.setEndTime(nowTime);
                alarmDAO.save(alarm);
            }
        }
    //单个设备的总报警时间计算 (单位毫秒)
    public long calculateTime(Device device){
        //得到所有的alarm，包括endTime为空的
        List<Alarm>  alarms=alarmDAO.findByDevice(device);
        HashMap<LocalDateTime,LocalDateTime> map= new HashMap<>();
        Long TotalTime=0l;  //总时长
        for (Alarm alarm :alarms){
            map.put(alarm.getCreateTime(),alarm.getEndTime());
        }

        for (Map.Entry<LocalDateTime,LocalDateTime> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":**********" + entry.getValue());
            if (entry.getValue() != null)
            TotalTime = LocalDateTimeUtils.getMillSecondByLocalDateTime(entry.getValue())-
                    LocalDateTimeUtils.getMillSecondByLocalDateTime(entry.getKey())+TotalTime;
        }
        return TotalTime;
    }
    //查找设备最新的repair集合，可指定有几个
    public List<Alarm> getLatestAlarms (Device device, int size){
        Sort sort = new Sort(Sort.Direction.DESC, "id");  //id倒序排序，最新的记录在最前面
        Pageable pageable = new PageRequest(0, size, sort);
        Page<Alarm> page= alarmDAO.findByDevice(device,pageable);
        List<Alarm> alarms =page.getContent();
        return  alarms ;
    }
}
